package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.framework.utils.HYCUtils;
import cn.huiyunche.base.service.interfaces.BFilesService;
import cn.huiyunche.base.service.interfaces.CAccntBillService;
import cn.huiyunche.base.service.mappers.BFilesMapper;
import cn.huiyunche.base.service.model.BFiles;
import cn.huiyunche.base.service.model.BFilesExample;
import cn.huiyunche.tools.basic.exceptions.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.List;

@Service
public class BFilesServiceImpl implements BFilesService {

    private static final Logger LOGGER = LoggerFactory.getLogger(BFilesServiceImpl.class);

    private static final Integer DIFF_HOURS = 24 * 60 * 60 * 1000;

    @Autowired
    private BFilesMapper bFilesMapper = null;

    @Autowired
    private CAccntBillService cAccntBillService = null;

    private CAccntBillService getCAccntBillService() {
        return this.cAccntBillService;
    }

    private BFilesMapper getBFilesMapper() {
        return this.bFilesMapper;
    }

    @Override
    public int add(BFiles bFiles) {
        LOGGER.error("add bFiles params bFiles : {}.", bFiles);
        try {
            return this.getBFilesMapper().insertSelective(bFiles);
        } catch (Exception e) {
            LOGGER.error("add bFiles error : {}.", e);
            throw new BusinessException("插入数据bFiles异常");
        }
    }

    @Override
    public BFiles selectByBillid(Long billId) {
        LOGGER.info("select bFiles params billId : {}.", billId);
        try {
            BFilesExample example = new BFilesExample();
            example.createCriteria().andBussIdEqualTo(billId);
            List<BFiles> list = this.getBFilesMapper().selectByExample(example);
            if (CollectionUtils.isNotEmpty(list)) {
                return list.get(0);
            }
        } catch (Exception e) {
            LOGGER.error("select bFiles params billId : {}, error : {}.", billId, e);
            throw new BusinessException("插入数据bFiles异常");
        }
        return null;
    }

    @Override
    public void returnFile(HttpServletRequest request, HttpServletResponse response, String billId, String time) throws FileNotFoundException, IOException {
        String sBillId = HYCUtils.decryptBankCard(billId);
        LOGGER.info("kyle buss upload excel params billId : {}, time : {}.", sBillId, time);
        long lBillId = NumberUtils.toLong(sBillId);
        BFiles bFiles = this.selectByBillid(lBillId);
        if (null != bFiles) {
            HSSFWorkbook wb = this.getCAccntBillService().generateExcel(lBillId);
            String fileRealName = URLEncoder.encode(bFiles.getRealName(), "UTF-8");
            if (fileRealName.length() > 150) {
                fileRealName = new String(bFiles.getRealName().getBytes("UTF-8"), "ISO8859-1");
            }

            // 判断链接24小时生效
            response.setCharacterEncoding("UTF-8");
            String sTime = HYCUtils.decryptBankCard(time + "");
            if (System.currentTimeMillis() - NumberUtils.toLong(sTime) <= DIFF_HOURS) {
                response.setContentType("application/vnd.ms-excel");
                response.setHeader("Content-Disposition", "attachment;filename=\"" + fileRealName + ".xls\"");
                LOGGER.info("kyle buss upload excel params billId : {}, time : {}.", sBillId, time);
                wb.write(response.getOutputStream());
            } else {
                PrintWriter pw = response.getWriter();
                StringBuffer sb = new StringBuffer();
                response.setContentType("text/html");
                sb.append("<!DOCTYPE html>").append("<html>").append("<head>").append("<title>账单下载</title>")
                        .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">")
                        .append("<meta name=\"viewport\" content=\"initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width\">")
                        .append("</head>").append("<body style=\"margin: 0;\">")
                        .append("<div style=\"background-color: #ff8213; color: #ffffff; text-align: center;\">")
                        .append("<p style=\"display: inline-block;\">账单下载</p>")
                        .append("</div>").append("<p style=\"color: #ff8213; text-align: center\">该链接已失效</p>")
                        .append("</body>").append("</html>");
                pw.write(sb.toString());
                pw.flush();
                pw.close();
            }
        }

        /** BFilesExample example = new BFilesExample();
         example.createCriteria().andBussIdEqualTo(NumberUtils.toLong(sBillId));
         List<BFiles> list = this.getBFilesMapper().selectByExample(example);
         LOGGER.info("kyle buss upload excel params billId : {}, time : {}, list : {}.", sBillId, time, list);
         if(list.size() > 0){
         BFiles bFiles = list.get(0);
         String path = bFiles.getPath();
         String fileName = bFiles.getFileName();
         String suffix = bFiles.getSuffix();
         File file = FileUtils.getFile(path, fileName+"."+suffix);
         LOGGER.info("kyle buss upload excel params billId : {}, time : {}, list : {}, path : {}, fileName : {}.", sBillId, time, list, path, fileName);

         String fileRealName = URLEncoder.encode(bFiles.getRealName(), "UTF-8");
         if(fileRealName.length()>150){
         fileRealName = new String(bFiles.getRealName().getBytes("UTF-8"), "ISO8859-1");
         }

         response.setContentType("application/vnd.ms-excel");
         response.setCharacterEncoding("UTF-8");
         response.setHeader("Content-Disposition", "attachment;filename=\"" + fileRealName + ".xls\"");

         IOUtils.copy(new FileInputStream(file), response.getOutputStream());
         } */
    }

    @Override
    public List<BFiles> selectByBillids(List<Long> billIds) {
        LOGGER.info("select bFiles params billIds : {}.", billIds);
        try {
            BFilesExample example = new BFilesExample();
            example.createCriteria().andBussIdIn(billIds);
            List<BFiles> list = this.getBFilesMapper().selectByExample(example);
            if (CollectionUtils.isNotEmpty(list) && list.size() >= billIds.size()) {
                return list;
            }
        } catch (Exception e) {
            LOGGER.error("select bFiles params billIds : {}, error : {}.", billIds, e);
            throw new BusinessException("插入数据bFiles异常");
        }
        return null;
    }

}